﻿using System;
using System.Text.RegularExpressions;

namespace Peak.ApplicationServices
{
  public class DurationParser
  {
    public static bool TryParse(string duration, out TimeSpan result)
    {
      if (!SmartParse(duration, out result))
        return TimeSpan.TryParse(duration, out result);
      else
        return true;
    }

    public static bool SmartParse(string duration, out TimeSpan result)
    {
      result = new TimeSpan();
      string[] splited = duration.Trim().Split(' ');
      if(splited.Length > 3 || splited.Length < 1)
        return false;

      decimal day = 0;
      decimal hour = 0;
      int minute = 0;

      foreach (string s in splited)
      {
        if (s.Contains("d"))
        {
          if(!decimal.TryParse(s.Replace("d", ""),out day))
            return false;

          continue;
        }

        if (s.Contains("m"))
        {
          if(!int.TryParse(s.Replace("m", ""),out minute))
            return false;

          continue;
        }

        if(!decimal.TryParse(s.Replace("h", "").Replace("g", ""),out hour))
          return false;
      }

      result = new TimeSpan(((long)(minute+hour*60+day*24*60))*10000000*60);
      return true;
    }   

    public static string ToString(TimeSpan timespan)
    {
      if (timespan.TotalHours == 0)
        return "0h";
      if (timespan.TotalHours < 1)
        return timespan.TotalMinutes + "m";
      else
        return Math.Round(timespan.TotalHours,2) + "h";
    }
  }
}
